import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.util.List;

/**
 * 多线程类
 */

//实现runable接口
public class ChatThread implements Runnable{

    private int count;
    private Socket s;
    private List<Socket> li;

    public ChatThread(Socket s, int count, List<Socket> li) {
        this.count = count;
        this.s = s;
        this.li = li;
    }


    @Override
    public void run() {
        BufferedReader br = null;
        BufferedWriter bw = null;

        try {
            // 使用输入输出流进行通信
            bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
            br = new BufferedReader(new InputStreamReader(s.getInputStream()));

            //接收客户端输入来的内容并打印
            String str = "ip:" + s.getInetAddress().getHostAddress()  + "-->主机"
                    + count +   "号";
            bw.write(str);
            bw.newLine();
            bw.flush();

            String line = null;
            while((line = br.readLine())!=null){
                if(!li.isEmpty()){
                    for(Socket soc : li){
                        BufferedWriter bw2 = new BufferedWriter(new OutputStreamWriter(soc.getOutputStream()));
                        bw2.write(str + "说：" + line);
                        bw2.newLine();
                        bw2.flush();
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
    }
}
